package com.cloud.form.api.translator;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.Shape;
import com.aspose.words.WrapType;
import com.cloud.form.api.entity.FormAssemblyInst;
import com.cloud.form.common.utils.MediaStorageHelper;

public class ImageTranslator {
	private static final Logger logger = LoggerFactory.getLogger(ImageTranslator.class);

	public static void translator(Document doc, String bookmark, String value, FormAssemblyInst inst) {
		BookmarkCollection bookMarks = doc.getRange().getBookmarks();
		@SuppressWarnings("unchecked")
		Iterator<Bookmark> it = bookMarks.iterator();
		JSONObject styObj = JSONObject.parseObject(inst.getStyleAttributes());
		int width = (int) (styObj.getIntValue("width") <= 0 ? 100 : styObj.getIntValue("width") * 0.75);
		int height = (int) (styObj.getIntValue("height") <= 0 ? 100 : styObj.getIntValue("height") * 0.75);
		DocumentBuilder builder = new DocumentBuilder(doc);
		while (it.hasNext()) {
			Bookmark mark = it.next();
			if (mark.getName().equals(bookmark)) {
				InputStream in = null;
				try {
					in = MediaStorageHelper.download(value.replace("/media/api/storage/download?path=", ""));
					BufferedImage image = ImageIO.read(in);
					mark.setText("");
					builder.moveToBookmark(mark.getName());
					Shape shape = builder.insertImage(image, RelativeHorizontalPosition.CHARACTER, 0,
							RelativeVerticalPosition.PARAGRAPH, 10, width, height, WrapType.NONE);
					shape.setBehindText(true);
				} catch (Exception e) {
					logger.error("图片控件渲染失败", e);
				} finally {
					try {
						if (null != in) {
							in.close();
						}
					} catch (Exception e2) {
					}
				}
			}
		}
	}

}
